/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core;

import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import com.googlecode.actorom.Actor;
import com.googlecode.actorom.Address;
import com.googlecode.actorom.CompletableFutureResult;
import com.googlecode.actorom.ExitActorMessage;
import com.googlecode.actorom.ExitReason;
import com.googlecode.actorom.FutureResult;
import com.googlecode.actorom.KillActorException;
import com.googlecode.actorom.RestartType;
import com.googlecode.actorom.Topology;
import com.googlecode.actorom.support.ActorExecutionException;
import com.googlecode.actorom.support.ActorInvocationException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class CoreActor implements Actor {

    private static final transient Logger LOG = LoggerFactory.getLogger(CoreActor.class);
    private final Topology topology;
    private final Address address;
    private final MessageQueue mailbox;
    private final ExitListener exitListener;
    private final Map<Address, Actor> links;
    private volatile boolean active;
    private CoreHandler handler;

    public CoreActor(Topology topology, Address address, Object handler, MessageQueue mailbox, ExitListener exitListener) {
        this.topology = topology;
        this.address = address;
        this.handler = new CoreHandler(topology, address, handler);
        this.mailbox = mailbox;
        this.exitListener = exitListener;
        links = new HashMap<Address, Actor>();
        active = false;
    }

    public boolean spawn() {
        synchronized (this) {
            if (!active) {
                boolean success = handler.handleOnSpawn();
                if (success) {
                    active = true;
                    return true;
                } else {
                    return false;
                }
            } else {
                throw new IllegalStateException("Actor at address " + address + " is already active!");
            }
        }
    }

    public boolean restart(ExitReason reason) {
        synchronized (this) {
            boolean restarted = false;
            if (handler.getRestartType().equals(RestartType.PERMANENT)) {
                restarted = handler.handleOnRestart();
            } else if (handler.getRestartType().equals(RestartType.TRANSIENT) && reason.equals(ExitReason.FAIL)) {
                restarted = handler.handleOnRestart();
            }
            if (restarted) {
                active = true;
                return true;
            } else {
                active = false;
                return false;
            }
        }
    }

    public void exit(ExitReason reason) {
        synchronized (this) {
            active = false;
            for (Actor linked : links.values()) {
                if (linked.isActive()) {
                    linked.send(new ExitActorMessage(address, reason));
                }
            }
            links.clear();
        }
    }

    public void handle(Object message, CompletableFutureResult future) {
        synchronized (this) {
            if (active) {
                try {
                    if (isExitActorMessage(message)) {
                        ExitActorMessage exitMessage = (ExitActorMessage) message;
                        if (exitMessage.getSender() != null) {
                            unlinkExitMessageSender(exitMessage.getSender());
                        }
                        Object result = handler.handleTrapExit(exitMessage);
                        future.completeWithResult(result);
                    } else {
                        Object result = handler.handleOnMessage(message);
                        future.completeWithResult(result);
                    }
                } catch (KillActorException ex) {
                    future.completeWithResult(null);
                    onKill();
                } catch (ActorExecutionException ex) {
                    future.completeWithException(ex);
                    onFail();
                }
            } else {
                future.completeWithException(new ActorExecutionException("The actor at address " + address + " seems not to be active!"));
            }
        }
    }

    public void swap(Object handler) {
        synchronized (this) {
            if (active) {
                CoreHandler tmp = new CoreHandler(topology, address, handler);
                boolean swapped = tmp.handleOnSwap();
                if (swapped) {
                    this.handler = tmp;
                } else {
                    throw new ActorInvocationException("Error trying to swap handler of actor at address " + address);
                }
            }
        }
    }

    public void link(Actor linkedActor) {
        synchronized (this) {
            if (active) {
                Address linkedAddress = linkedActor.getAddress();
                if (address.isNeighborOf(linkedAddress)) {
                    if (!links.containsKey(linkedAddress)) {
                        links.put(linkedAddress, linkedActor);
                    }
                } else {
                    throw new ActorInvocationException("The actor at address " + address + " doesn't belong to the same topology of linked actor at address: " + linkedAddress);
                }
            } else {
                throw new ActorInvocationException("The actor at address " + address + " seems not to be active!");
            }
        }
    }

    public void unlink(Actor linkedActor) {
        synchronized (this) {
            if (active) {
                Address linkedAddress = linkedActor.getAddress();
                if (address.isNeighborOf(linkedAddress)) {
                    if (links.containsKey(linkedAddress)) {
                        links.remove(linkedAddress);
                    }
                } else {
                    throw new ActorInvocationException("The actor at address " + address + " doesn't belong to the same topology of linked actor at address: " + linkedAddress);
                }
            } else {
                throw new ActorInvocationException("The actor at address " + address + " seems not to be active!");
            }
        }
    }

    public void send(Object message) throws ActorInvocationException {
        if (active) {
            try {
                CompletableFutureResult future = new NullFutureResult();
                mailbox.put(new MessageHandle(address, message, future));
            } catch (InterruptedException ex) {
                throw new ActorInvocationException("Unable to send message to actor at address: " + address, ex);
            }
        } else {
            throw new ActorInvocationException("The actor at address " + address + " seems not to be active!");
        }
    }

    public FutureResult send(Object message, long timeout, TimeUnit unit) throws ActorInvocationException {
        if (active) {
            try {
                CompletableFutureResult future = new CoreFutureResult(unit.toNanos(timeout));
                mailbox.put(new MessageHandle(address, message, future));
                return future;
            } catch (InterruptedException ex) {
                throw new ActorInvocationException("Unable to send message to actor at address: " + address, ex);
            }
        } else {
            throw new ActorInvocationException("The actor at address " + address + " seems not to be active!");
        }
    }

    public Address getAddress() {
        return address;
    }

    public boolean isActive() {
        return active;
    }

    private boolean isExitActorMessage(Object message) {
        return message.getClass().equals(ExitActorMessage.class);
    }

    private void unlinkExitMessageSender(Address sender) {
        links.remove(sender);
    }

    private void onKill() {
        try {
            active = false;
            handler.handleOnKill();
        } finally {
            exitListener.onKill(this);
        }
    }

    private void onFail() {
        active = false;
        exitListener.onFail(this);
    }
}
